module.exports = app => {
  const express = require('express')
  const router = express.Router({
    mergeParams: true
  })
  /*======================== 定义接口以及方法 start ========================*/
  let result = {
    code: 200,
    msg: "请求成功"
  }
  // 创建数据
  router.post('/addMaganerInfo', (req, res) => {
    req.ModelData.create(req.body)
    res.json({ ...result })
  })
  // 获取数据
  router.get('/getManagerInfo', async (req, res) => {
    const model = await req.ModelData.find().limit()
    res.json({ ...result, data: model })
  })
  // 修改数据
  router.post('/editManagerInfo', async (req, res) => {
    const time = req.body.prop
    const arrArr = req.body.arrArr;
    const schedule = req.body.schedule;

    if (schedule[`year_${time.year}`].months[time.month].weeks[time.week][time.day].arrange != null) {
      schedule[`year_${time.year}`].months[time.month].weeks[time.week][time.day].arrange.push(arrArr)
    }
    else {
      schedule[`year_${time.year}`].months[time.month].weeks[time.week][time.day].arrange = [arrArr]
    }

    const managerInfos = require("../models/ManagerInfos")

    const target = `schedule.year_${time.year}.months.${time.month}.weeks`

    await managerInfos.findOneAndUpdate(
      {
        managerName: "Joe"
      },
      {
        $set: {
          [target]: schedule[`year_${time.year}`].months[time.month].weeks
        }
      }
    )

    res.json(true)
  })
  // 删除数据
  router.post('/deleteManagerInfo', (req, res) => {
    req.ModelData.findByIdAndDelete(req.body._id, req.body)
    res.json({ ...result })
  })
  /*======================== 定义接口以及方法 end ========================*/

  const resourceMiddleWare = async (req, res, next) => {
    req.ModelData = await require(`../models/${req.params.resource}`) // 给请求绑定原型的名称并引入数据库原型,
    next()
  }
  app.use('/api/rest/:resource', resourceMiddleWare, router)
}